package com.aivin.lib_login.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.aivin.lib_base.tool.MyDeviceInforHelper;
import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_login.R;
import com.aivin.lib_login.bean.PicBean;
import com.aivin.lib_login.ui.RecyclerViewFastScroller;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import java.util.ArrayList;
import java.util.List;


public class PicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  implements RecyclerViewFastScroller.BubbleTextGetter {
    private int mSelectedItem =  0;
    private List<PicBean> datas;
    private PicSelectCallBack selectCallBack;
    private Context context ;
    private int columnCount ;

    public PicAdapter(List<PicBean> datas, int columnCount ,PicSelectCallBack selectCallBack) {
        if(datas==null){
            datas =new ArrayList<>();
        }
        this.datas = datas;
        this.columnCount = columnCount;
        this.selectCallBack = selectCallBack;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if(context==null){
            context=viewGroup.getContext() ;
        }
        if (viewType == 0) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.video_item, viewGroup, false);
            return new ChooseHolder(view);
        } else {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.video_loadmore, viewGroup, false);
            return new FooterHolder(view);
        }
    }




    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof ChooseHolder) {
            ChooseHolder chooseHolder = (ChooseHolder) viewHolder;
            chooseHolder.picIndexShow.setText(String.valueOf(position+1));

            PicBean bean =  datas.get(position);
            //WkLog.showErrorLog("updateImageScale  .... bean.getScale()="+bean.getScale() +"  "+ bean.isUpdated()+"  "+ bean.getPicUrl() );

            /*final ViewGroup.LayoutParams layoutParams =chooseHolder.picShowIv.getLayoutParams();
            layoutParams.width = (MyDeviceInforHelper.getScreenWidth(context)/columnCount) ;
            float scalK =  bean.getScale()==-1 ? 1:  bean.getScale() ;
            layoutParams.height = (int) (layoutParams.width / scalK);
            chooseHolder.picShowIv.setLayoutParams(layoutParams);  // !!!!*/



            final ViewGroup.LayoutParams layoutParams =chooseHolder.picShowIv.getLayoutParams();
            layoutParams.width = (MyDeviceInforHelper.getScreenWidth(context) / (columnCount+1) ) ;
            WkLog.showLog("bean.getScale()="+bean.getScale());
            layoutParams.height = (int) (layoutParams.width /  bean.getScale());
            chooseHolder.picShowIv.setLayoutParams(layoutParams);


            /*Glide.with(context)
                    .load(bean.getPicUrl())
                    .placeholder(R.mipmap.loading2)
                    .error(R.mipmap.load_error)
                    .thumbnail(0.5f) // 缩略图为原图的 0.1倍
                    .transition(new DrawableTransitionOptions().crossFade())
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            if(e!=null){
                                WkLog.showLog("onBindViewHolder onLoadFailed=="+e.getMessage());
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(chooseHolder.picShowIv);*/

        } else if (viewHolder instanceof FooterHolder) {
            FooterHolder holder = (FooterHolder) viewHolder;
            if(hasMoreData){
                holder.hasMoreDataTv.setText("上滑加载更多");
            }else{
                holder.hasMoreDataTv.setText("---加载完毕---");
            }
        }
    }


    @Override
    public String getTextToShowInBubble(final int pos) {
        return  String.valueOf(pos);
    }


    private int updatedCount = -1 ;
    private int needUpdateCount = 0 ;
    private void updateImageScale(List<PicBean> pageData) {
        if(pageData==null){
            return;
        }
        needUpdateCount = pageData.size() ;
        updatedCount =0 ;
        WkLog.showLog("updateImageScale 图片长宽 开始更新 ....=="+ pageData.size() );
        for ( PicBean picBean : pageData) {
            loadPic2GetScale(picBean ,pageData);
        }
        WkLog.showLog("updateImageScale 图片长宽更新完毕....==" );
    }


    /**
     * 最好是提前加载，而不是放到  onBindViewHolder 再去加载，
     * 因为网络图片加载需要时间。
     */
    private void loadPic2GetScale(PicBean picBean ,List<PicBean> pageData){
        WkLog.showLog("updateImageScale 更新中 ....==" );

        if(picBean.isUpdated()){
            WkLog.showLog("updateImageScale 更新中, 无需更新=="+picBean.getScale() );
            showUpdateProgress("无需更新" ,pageData);
            return;
        }

        Glide.with(context)
                .load(picBean.getPicUrl())
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        showUpdateProgress("下载失败 "+ e.getMessage()+"  "+picBean.getPicUrl()  ,pageData);
                        picBean.setScale(1);
                        picBean.setUpdated(true);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        float scale = resource.getIntrinsicWidth() / (float) resource.getIntrinsicHeight();
                        picBean.setScale(scale); // k = w / h
                        picBean.setUpdated(true);

                        showUpdateProgress("更新成功"  ,pageData);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }


    private void showUpdateProgress(String tag ,List<PicBean> pageData){
        updatedCount++ ;
        WkLog.showLog("更新进度="+ updatedCount+"  /"+ needUpdateCount +"  "+tag);

        if(updatedCount>= needUpdateCount){
            WkLog.showLog("更新进度= 更新完成。" );
            datas.addAll(pageData) ;
            notifyDataSetChanged();
        }
    }


    @Override
    public int getItemViewType(int position) {
        if(datas==null){
            return 1;
        }

        if (position == datas.size()) {
            return 1;
        } else {
            return 0;
        }
    }

    //提供给外部调用的方法 刷新数据
    public void updateData(List<PicBean> pageData) {
        updateImageScale(pageData);
    }



    private boolean hasMoreData = true ;
    public void setHasMoreData(boolean hasMoreData) {
        this.hasMoreData = hasMoreData;
    }



    @Override
    public int getItemCount() {
        return datas==null?  1:  datas.size()+1;
    }

    class ChooseHolder extends RecyclerView.ViewHolder {
        ImageView picShowIv;
        TextView picIndexShow ;
        ChooseHolder(View itemView) {
            super(itemView);
            picShowIv = itemView.findViewById(R.id.picShowIv);
            picIndexShow = itemView.findViewById(R.id.picIndexShow);
            View.OnClickListener clickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectedItem = getAdapterPosition();
                    selectCallBack.setSelectedCallBack(mSelectedItem);
                }
            };
            picShowIv.setOnClickListener(clickListener);
        }
    }

    // region 布局测试
    public class FooterHolder extends RecyclerView.ViewHolder {
        TextView hasMoreDataTv ;
        FooterHolder(View itemView) {
            super(itemView);
            hasMoreDataTv = itemView.findViewById(R.id.hasMoreDataTv) ;

        }
    }
    // endregion 布局测试

    public interface PicSelectCallBack {
        void setSelectedCallBack(  int index ) ;
    }

}


